package models

import (
	"class-server/basic/config"
	"gorm.io/gorm"
	"time"
)

type Classes struct {
	Id         uint           `gorm:"column:id;type:bigint UNSIGNED;primaryKey;not null;" json:"id"`
	ClassName  string         `gorm:"column:class_name;type:varchar(255);comment:课程名称;not null;" json:"class_name"` // 课程名称
	Author     string         `gorm:"column:author;type:varchar(255);not null;" json:"author"`
	ClassImg   string         `gorm:"column:class_img;type:varchar(255);comment:视频封面;not null;" json:"class_img"`                               // 视频封面
	ClassUrl   string         `gorm:"column:class_url;type:varchar(255);comment:视频链接;not null;" json:"class_url"`                               // 视频链接
	ClassPrice uint           `gorm:"column:class_price;type:int UNSIGNED;comment:课程价格;not null;default:0;" json:"class_price"`                 // 课程价格
	VipPrice   uint           `gorm:"column:vip_price;type:int UNSIGNED;comment:会员价格;not null;default:0;" json:"vip_price"`                     // 会员价格
	TypesId    uint           `gorm:"column:types_id;type:int UNSIGNED;comment:课程分类ID;not null;default:0;" json:"types_id"`                     // 课程分类ID
	BuyStatus  uint           `gorm:"column:buy_status;type:int UNSIGNED;comment:是否购买：1：已购买 2：未购买;not null;default:0;" json:"buy_status"` // 是否购买：1：已购买 2：未购买
	CreatedAt  time.Time      `gorm:"column:created_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"`
	UpdatedAt  time.Time      `gorm:"column:updated_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"`
	DeletedAt  gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);default:NULL;" json:"deleted_at"`
}

func (c *Classes) TableName() string {
	return "classes"
}

// 课程详情
func (c *Classes) GetClassDetail() error {
	return config.DB.Where("buy_status = ?", c.BuyStatus).Limit(1).Find(&c).Error
}

// 课程分类展示
func (c *Classes) GetClassList(page, pageSize int) (classList []*Classes, err error) {
	err = config.DB.Where("types_id = ?", c.TypesId).Scopes(Paginate(page, pageSize)).Find(&classList).Error
	return
}

// 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
